from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
import time

# # 1. 初始化浏览器（全局驱动，只初始化一次）
# service = ChromeService(executable_path="C:\\Program Files\\Google\\Chrome\\Application\\chromedriver.exe")
# options = webdriver.ChromeOptions()
# options.add_experimental_option("excludeSwitches", ["enable-automation"])  # 禁用自动化提示
# driver = webdriver.Chrome(service=service, options=options)
#
base_url = "https://www.jisilu.cn/data/convert_bond_detail/"


def get_data_by_selenium(driver,bond_id):
    """获取单只可转债数据，不关闭浏览器"""
    print(f"获取可转债本息===> {bond_id}")
    full_url = base_url + str(bond_id)

    try:
        driver.get(full_url)  # 打开目标页面
        # 等待表格加载（注意：原代码中用了ID="qflag_info"，需确认是否正确）
        print("等待表格加载...")
        table = WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.ID, "qflag_info"))  # 确保ID正确
        )
        print("表格加载完成")
        return table.text

    except Exception as e:
        print(f"获取{bond_id}数据失败：{str(e)}")
        return None


# if __name__ == "__main__":
#     try:
#         # 示例：获取两只可转债数据（可多次调用）
#         data1 = get_data_by_selenium(113690)
#         print(f"113690数据：\n{data1[:200]}...\n")  # 打印前200字符
#
#         time.sleep(2)  # 模拟间隔，避免请求过快
#
#         data2 = get_data_by_selenium(123188)
#         print(f"123188数据：\n{data2[:200]}...")
#
#     finally:
#         # 所有操作完成后，最后关闭浏览器（只调用一次）
#         # driver.quit()
#         print("\n浏览器已关闭")
